package com.yunying.rispro.exception;

import com.yunying.rispro.util.JsonResponseBody;
import com.yunying.rispro.util.JsonResponseStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * SpringMVC全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResponseBody<?> exceptionHandler(Exception e){
        e.printStackTrace();
        JsonResponseBody<?> jsonResponseBody=null;
        // 判断异常是否是自定义的业务类异常
        if(e instanceof BusinessException){
            BusinessException ex= (BusinessException) e;
            jsonResponseBody=new JsonResponseBody<>(ex.getJsonResponseStatus());
        }else if (e instanceof BindException){
            BindException ex= (BindException) e;
            // 获取注解上定义的message消息
            String msg = ex.getFieldError().getDefaultMessage();
            jsonResponseBody=new JsonResponseBody<>();
            jsonResponseBody.setMsg(msg);
            jsonResponseBody.setCode(100999);
        }else{
            jsonResponseBody=new JsonResponseBody<>(JsonResponseStatus.ERROR);
        }
        return jsonResponseBody;
    }
}
